package com.my.screenadapter.hook;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.my.screenadapter.Base.BaseActivity;
import com.my.screenadapter.R;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by zyj 2019-2-28 10:21:55
 * Function ： Hook demo
 */
public class Hook_01Activity extends BaseActivity {

    @BindView(R.id.button1)
    Button button1;

    @Override
    protected void init() {
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: ---- get");
            }
        });

        try {
            hookOnClickListener(button1);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_hook_01;
    }

    public static void hookOnClickListener(View view) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException, NoSuchFieldException {
        //1 得到 ListenerInfo 对象
        Method getListenerInfo = View.class.getDeclaredMethod("getListenerInfo");
        getListenerInfo.setAccessible(true);
        Object objListenerInfo = getListenerInfo.invoke(view);//得到 ListenerInfo 对象
        //2 得到原始的 OnClickListener 事件的方法 的对象
        Class<?> listenerInfoClz  = Class.forName("android.view.View$ListenerInfo");
        Field mOnClickListener = listenerInfoClz.getDeclaredField("mOnClickListener");
        mOnClickListener.setAccessible(true);
        View.OnClickListener originOnClickListener = (View.OnClickListener) mOnClickListener.get(objListenerInfo);//得到  OnClickListener 对象。
        //3 用 Hook 代理类 替换原始的 OnClickListener
        HookedClickListenerProxy hookedClickListenerProxy = new HookedClickListenerProxy(originOnClickListener);
        mOnClickListener.set(objListenerInfo,hookedClickListenerProxy);

    }

}
